//
//  MyUIViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/6.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "MyUIViewController.h"
#import "MyHeaderTableViewCell.h"
#import "MyRightView.h"
#import "TabbarTableViewCell.h"
#import "MyNormalMode.h"
#import "MyNormalTableViewCell.h"
#import "MyInfoTableViewController.h"
#import "MyHeaderView.h"
#import "IndexRightButton.h"
#import "MessageListTableViewController.h"
#import "SettingTableViewController.h"
#import "MyCarViewController.h"
#import "MyZTTableViewController.h"
#import "FavCuSmerTableViewController.h"
#import "UserModel.h"
#import "HistoryTableViewController.h"
#import "MyWinViewController.h"
#import "FavCarViewController.h"
#import "CheckCarViewController.h"
#import "MyFindBuyViewController.h"
#import "MyFindWinViewController.h"
#import "ToolBarModel.h"
#import "Puser.h"
#import "CarDetailViewController.h"
#import "GotoViewController.h"
#define heightimageHeight 129
#define headerHeight 480
@interface MyUIViewController ()<UITableViewDelegate,UITableViewDataSource,rightViewClickDelegate,RightButtonClickDelegate,MyheaderViewClickDelegate,TabbarCellClickDelegate>
    
    
@property (nonatomic,weak) MyHeaderView *header;

@property (nonatomic,strong) NSArray *dataarray;
@property (nonatomic,strong) UIActivityIndicatorView *indicator;
@property (nonatomic,strong) Puser *puser;
@property (nonatomic,strong) IndexRightButton *right;

@end

@implementation MyUIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    self.tableView.contentInset=UIEdgeInsetsMake(0.5*headerHeight, 0, 44, 0);
    self.tableView.backgroundColor=bgGarycolor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor=UIColorFromRGB(0xe6e6e6);
   UIActivityIndicatorView *indicatory= [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 44)];
    [view addSubview:indicatory];
    [indicatory setCenter:CGPointMake(20, 22)];
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    self.indicator=indicatory;
    self.navigationItem.titleView=view;
    MyHeaderView *myheader=[MyHeaderView header];
    myheader.y=-headerHeight-20;
    myheader.height=headerHeight;
    myheader.delegate=self;
    self.header=myheader;
    [self.tableView addSubview:myheader];
    [self setupright];
    
    
}


- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    
    NSDictionary *content=extras[@"content"];
    if (content!=nil) {
        self.right.reddot.hidden=NO;
    }
}

-(Puser *)puser{
    if (_puser==nil) {
        _puser=[Puser getUser];
    }
    return _puser;
}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self getUserInfo];
}

-(void)getUserInfo{
    [self.indicator startAnimating];
//    NSDictionary *userinfo=[DbUtils getuserinfo];
//    UserModel *mode=[UserModel userWithDict:userinfo];
    
  
    
    Puser *user=[Puser getUser];
    int power=[user.power intValue];
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    NSString *type;
    NSString *action;
    if (power<5) {
        type=@"person";
        action=@"p_info";
        params[@"user_id"]=user.user_id;
    }else if(power<9){
        type=@"company";
        params[@"com_id"]=user.com_id;
        action=@"c_info";
        if (![user.parent_id isEqualToString:@"0"]) {
            params[@"pid"]=user.parent_id;
        }
    }
    params[@"user_type"]=type;
   
    params[@"action"]=action;
    [PostUitls Post:userinfourl parameters:params success:^(id response) {
       
        NSDictionary *dict=response;
        NSDictionary *data=dict[@"data"];
        if (data !=nil) {
//            [DbUtils addUserInfo:data];
            Puser *tuser= [Puser userWithDict:data WithPower:nil];
//            mode.power=power;
            [self setupdata:tuser];
        }
        [self.indicator stopAnimating];
        
        
    } failure:^(NSError *error) {
        [self.indicator stopAnimating];

    }];
}



-(void)HeadViewclickWithIndex:(NSInteger)index{
       if (index==0) {
           FavCarViewController *fcarvc=[FavCarViewController Viewcontroller];
           [self.navigationController pushViewController:fcarvc animated:YES];
    }
    
    if (index==1) {
        FavCuSmerTableViewController *favc=[FavCuSmerTableViewController viewcontroller];
        [self.navigationController pushViewController:favc animated:YES];
    }
   
    if (index==2) {
        int power=[self.puser.power intValue ];
        
        if (power==1||power==5||power==8) {
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText=@"您已是认证商家";
            hud.mode = MBProgressHUDModeText;
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
        }else if (power==6||power==3){
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText=CheckIngString;
            hud.mode = MBProgressHUDModeText;
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
        }else if(power==4||power==2)
        {
            GotoViewController *gotovc=[GotoViewController   viewcontroller];
            
            [self.navigationController pushViewController:gotovc   animated:YES];
        }
    }

    

}

-(void)TabbarClickWithIndex:(NSInteger)index{
    NSLog(@"%ld",index);
    if (index==0) {
        MyZTTableViewController *myztvc=[MyZTTableViewController viewcontroller];
        [self.navigationController pushViewController:myztvc animated:YES];
    }else{
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"暂未开放，敬请期待！";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
    }
//    if (index==2) {
//        CheckCarViewController *chvc=[CheckCarViewController Viewcontroller];
//        [self.navigationController pushViewController:chvc animated:YES];
//    }
    
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    CGFloat y=-0.5*headerHeight-scrollView.contentOffset.y;
    NSLog(@"%f",y);

}





-(void)rightclick{
    MessageListTableViewController *message=[MessageListTableViewController message];
    [self.navigationController pushViewController:message animated:YES];
}
-(void)setupdata:(Puser *)mode{
  
    
    ToolBarModel *toolbar;
    int power=[mode.power intValue];
    MyNormalMode *ziliaomode=[[MyNormalMode alloc]init];
    ziliaomode.image=[UIImage imageNamed:@"ico-zl"];
    ziliaomode.name=@"我的资料";
    ziliaomode.block=^{
        MyInfoTableViewController *myif=[XHMianStory instantiateViewControllerWithIdentifier:@"myif"];
        myif.user=mode;
        [self.navigationController pushViewController:myif animated:YES];
    };
    MyNormalMode *liulanmode=[[MyNormalMode alloc]init];
    liulanmode.image=[UIImage imageNamed:@"ico_myhistroy"];
    liulanmode.name=@"最近浏览";
    liulanmode.block=^{
        HistoryTableViewController *history=[[HistoryTableViewController alloc]init];
        history.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:history animated:YES];
    };
    MyNormalMode *cheyaunmode=[[MyNormalMode alloc]init];
    cheyaunmode.image=[UIImage imageNamed:@"ico_mycar"];
    cheyaunmode.name=@"我的车源";
    cheyaunmode.block=^{
        MyCarViewController *cavc=[[MyCarViewController alloc]init];
        cavc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:cavc animated:YES];
    };
    MyNormalMode *qbmode=[[MyNormalMode alloc]init];
    qbmode.image=[UIImage imageNamed:@"ico-qb"];
    qbmode.name=@"我的抢标";
    qbmode.block=^{
        MyWinViewController *winvc=[MyWinViewController ViewController];
        [self.navigationController pushViewController:winvc animated:YES];
    };
    MyNormalMode *qgmode=[[MyNormalMode alloc]init];
    qgmode.image=[UIImage imageNamed:@"ico_qg"];
    qgmode.name=@"我的求购";
    qgmode.block=^{
        MyFindBuyViewController *myfind=[MyFindBuyViewController Viewcontroller];
        [self.navigationController pushViewController:myfind animated:YES];
    };
    MyNormalMode *zbmode=[[MyNormalMode alloc]init];
    zbmode.image=[UIImage imageNamed:@"ico-zhaobiao"];
    zbmode.name=@"我的招标";
    zbmode.block=^{
        MyFindWinViewController *myfinwin=[MyFindWinViewController ViewController];
        [self.navigationController pushViewController:myfinwin animated:YES];
    };
    if (power!=1&&power!=5&&power!=9&&power!=8) {
         self.dataarray=@[@[ziliaomode,liulanmode]];
    }else if(power!=9){
    
        toolbar =[[ToolBarModel alloc]init];
      self.dataarray=@[@[toolbar],@[ziliaomode,liulanmode],@[cheyaunmode,qbmode],@[qgmode,zbmode]];
    }
    
    self.header.puser=mode;
    
    [self.tableView reloadData];
    
    
}
-(void)clickWithTag:(NSInteger)tag{
    NSLog(@"%ld",tag);
    [self.navigationController.tabBarController.navigationController popToRootViewControllerAnimated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
        NSArray *array=self.dataarray[indexPath.section];
        MyNormalMode *mode=array[indexPath.row];
        if (mode.block) {
            mode.block();
        }
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSInteger state= [XHUserDeflaut integerForKey:NotReadState];
    if (state==0) {
        self.right.reddot.hidden=YES;
    }else{
        self.right.reddot.hidden=NO;
    }
    [self setupNav:YES];
}
CGFloat calculateSlope(CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2)
{
    return (y2 - y1) / (x2 - x1);
}

CGFloat calculateConstant(CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2)
{
    return (y1*(x2 - x1) - x1*(y2 - y1)) / (x2 - x1);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setupright{
    IndexRightButton *leftitem=[IndexRightButton right];
    leftitem.rightclickdelegate=self;
    UIBarButtonItem *leftbaritem=[[UIBarButtonItem alloc]initWithCustomView:leftitem];
    self.navigationItem.leftBarButtonItem=leftbaritem;
    UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ico-sz"] style:UIBarButtonItemStyleDone target:self action:@selector(settingclick)];

    self.navigationItem.rightBarButtonItem=rightitem;
}
-(void)settingclick{
    SettingTableViewController *setting=[SettingTableViewController setting];
    [self.navigationController pushViewController:setting animated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataarray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array=self.dataarray[section];
    return  array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.dataarray[indexPath.section];
    MyNormalMode *mode=array[indexPath.row];
    if ([mode isKindOfClass:[ToolBarModel class]]) {
        TabbarTableViewCell *cell=[TabbarTableViewCell cell];
        cell.delegate=self;
        return cell;
    }else{
    
        MyNormalTableViewCell *cell=[MyNormalTableViewCell cellWithTablview:tableView];
               cell.imageView.image=mode.image;
        cell.textLabel.text=mode.name;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = bgGarycolor;
    
    // Text Color
  
    
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.dataarray[indexPath.section];
    MyNormalMode *mode=array[indexPath.row];
    if ([mode isKindOfClass:[ToolBarModel class]]) {
        return 60;
    }else{
        return 44;
    }
}
-(void)setupNav:(BOOL)isTOP{
    if (isTOP) {
        UIImage *clearimage= [UIImage imageNamed:@"v_line"];
        [self.navigationController.navigationBar setBackgroundImage:clearimage forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTranslucent:YES];
        [self.navigationController.navigationBar setShadowImage:clearimage];
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    }else{
        UIImage *detail= [UIImage imageNamed:@"detail_navbg"];
        [self.navigationController.navigationBar setBackgroundImage:detail forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTranslucent:YES];
        
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
        
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
